﻿using LitJson;
using LNet;
using OestsCommon.Model;
using OestsDataBase;
using OestsServer.Managers;
using OestsServer.Net;

namespace OestsServer.Handlers.UnityHandlers
{
    public class LoginUnityHandler : HandlerBase<UnityClientChannel>
    {
        public override PacketKey PKey
        {
            get
            {
                return PacketKey.Login;
            }
        }

        public override void Execute(UnityClientChannel client, Request packet)
        {
            base.Execute(client, packet);
            ResponsePacket = new Response(packet);

            if (packet.RequestSubCode == SubCode.None)
            {
                LoginNone(client, packet);
            }

        }
        private void LoginNone(UnityClientChannel client, Request packet)
        {
            DP<ProjectType, User> data = JsonMapper.ToObject<DP<ProjectType, User>>(packet.DataStr);
            client.ProjectType = data.Value1;
            User u = data.Value2;

            if (u.DBid > 0)
            {
                //登录成功
                client.SetUserData(u);
                //client.UpdateLoginTime();
                ResponsePacket.DataObject = u;
                ResponsePacket.ReturnCode = ReturnCode.Success;
                client.Send(ResponsePacket);

                return;
            }

            User UserDB = UserDAL.GetUser(u.Number);

            /////////////////// 用户验证/////////////////////

            //检查用户信息
            if (!CheckUesrInfoHandler(client, u, UserDB))
            {
                return;
            }
            //检查用户是否在线
            if (client.CheckUserIsExist(/*u.Type,*/ UserDB.DBid))
            {
                AreadyOnlineHandler(client, u);
                return;
            }

            bool bSuccess = true;
            switch (UserDB.Type)
            {
                case UserType.Admin:
                case UserType.Teacher:
                    bSuccess = UnStudentLogin(client, u, UserDB);
                    break;
                case UserType.Student:
                    bSuccess = StudentLogin(client, u, UserDB);
                    break;
            }
            if (bSuccess)
            {
                //记录登录时间
                client.UpdateLoginTime();
                // client.UpdateLogoutTime();
            }


        }

        private bool CheckUesrInfoHandler(UnityClientChannel client, User u, User dbUser)
        {
            if (dbUser == null)
            {
                ResponsePacket.DataObject = u;
                ResponsePacket.ReturnCode = ReturnCode.Fail;
                ResponsePacket.RetrunMessage = "用户不存在！";
                client.Send(ResponsePacket);
                return false;
            }
            if (u.Password != dbUser.Password)
            {
                ResponsePacket.DataObject = u;
                ResponsePacket.ReturnCode = ReturnCode.Fail;
                ResponsePacket.RetrunMessage = "密码错误！";
                client.Send(ResponsePacket);
                return false;
            }
            return true;
        }

        private void AreadyOnlineHandler(ClientChannel client, User u)
        {
            ResponsePacket.DataObject = u;
            ResponsePacket.ReturnCode = ReturnCode.Fail;
            ResponsePacket.RetrunMessage = "该用户已经在线！";
            client.Send(ResponsePacket);
        }

        /// <summary>
        /// 非学生登录 返回User
        /// </summary>
        /// <param name="client"></param>
        /// <param name="u"></param>
        /// <param name="dbUser"></param>
        private bool UnStudentLogin(ClientChannel client, User u, User dbUser)
        {
            //登录成功处理
            client.SetUserData(dbUser);
            ResponsePacket.DataObject = dbUser;
            ResponsePacket.ReturnCode = ReturnCode.Success;
            client.Send(ResponsePacket);
            return true;
        }


        private bool StudentLogin(UnityClientChannel client, User u, User dbUser)
        {
            // DP<TrainingEnvironment,int, int> env = AdminDAL.GetTrainingEnvironment();//TODO:测试注释
            //  DP<TrainingEnvironment,int, int> env = new DP<TrainingEnvironment, int, int>(TrainingEnvironment.Normal,0,0);//TODO:测试注释

            StudentSuccessLoginHandler(client,/* env.Value1, */dbUser);
            return true;


            // if (env.Value1 == TrainingEnvironment.Normal)
            // {
            //  StudentSuccessLoginHandler(client, env.Value1, dbUser);
            //  return true;
            // }
            // else
            // {
            //if((int)client.ProjectType == env.Value2)
            //{
            //    if (!CheckStudentInExam(env.Value1, env.Value3, dbUser.DBid))
            //    {
            //        ResponsePacket.DataObject = null;
            //        ResponsePacket.ReturnCode = ReturnCode.Fail;
            //        ResponsePacket.RetrunMessage = "当前为考试环境，你未加入任何考试，请联系教员！";
            //        client.Send(ResponsePacket);
            //        return false;
            //    }
            //    else
            //    {
            //        StudentSuccessLoginHandler(client, env.Value1, dbUser);
            //        return true;
            //    }
            //}
            //else
            //{
            //    ResponsePacket.DataObject = null;
            //    ResponsePacket.ReturnCode = ReturnCode.Fail;
            //    ResponsePacket.RetrunMessage = "当前为考试环境，你未加入任何考试，请联系教员！";
            //    client.Send(ResponsePacket);
            //    return false;
            //}


            //}

        }

        private void StudentSuccessLoginHandler(ClientChannel client,/* TrainingEnvironment env, */User dbUser)
        {
            //登录成功处理
            client.SetUserData(dbUser);
            // ResponsePacket.DataObject = new DP<TrainingEnvironment, User>(env, dbUser);
            ResponsePacket.DataObject = dbUser;
            ResponsePacket.ReturnCode = ReturnCode.Success;
            client.Send(ResponsePacket);

            //通知管理教员上线
            if (client.User.Type == UserType.Student)
            {
                Student st = client.User as Student;
                st.OnLine = true;
                TeacherManager.Instance.NotifyTeacherStOnlineState(st);
            }
        }


        /// <summary>
        /// 检查学生是否加入考试
        /// </summary>
        /// <param name="studentId"></param>
        /// <returns></returns>
        private bool CheckStudentInExam(TrainingEnvironment env, int paperId, int studentId)
        {
            //获取当前培训环境

            //if (env == TrainingEnvironment.OperateExam)
            //{
            //    return StudentExamDAL.CheckStudentiInExam(studentId, paperId);
            //}
            //else 
            //{
            //    return StudentTheoryDAL.CheckStudentiInExam(studentId, paperId);
            //}
            return true;

        }



        /// <summary>
        /// Unity端命令启动
        /// </summary>
        /// <param name="client"></param>
        /// <param name="packet"></param>
        private void LoginCommand(ClientChannel client, Request packet)
        {
            User u = JsonMapper.ToObject<User>(packet.DataStr);
            //验证是否已登录平台



        }

    }
}